package com.verisette.ncos.service.master.bizunit;

import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;

import org.corp.agi.common.exception.BusinessException;
import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.service.bizunit.CommonBusinessUnit;
import org.corp.common.util.security.Encrypter;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.dao.UserProfileManagementDAO;
import com.verisette.ncos.persistence.domain.MasterUserGroupToUserProfile;
import com.verisette.ncos.persistence.domain.MasterUserProfile;

public class EditUserProfileManagementBU extends CommonBusinessUnit {

	private Logger logger = Logger.getLogger(EditUserProfileManagementBU.class);
	
	private Encrypter encrypter;
	@Autowired
	@Required
	public void setEncrypter(@Qualifier("encrypter")Encrypter encrypter) {
		this.encrypter = encrypter;
	}
	
	private UserProfileManagementDAO userProfileManagementDAO;
	@Required
	@Autowired
	public void setUserProfileManagementDAO(UserProfileManagementDAO userProfileManagementDAO) {
		this.userProfileManagementDAO = userProfileManagementDAO;
	}
	
	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
			
		Map<String, Object> inputMap = (Map<String, Object>)processContext.getValueObject();
		MasterUserProfile userProfile = (MasterUserProfile)inputMap.get(ProjectConstant.USER_PROFILE);
		String[] assignedRoles = (String[])inputMap.get(ProjectConstant.USER_PROFILE_ASSIGNED_ROLE);
		//String oldPassword = (String)inputMap.get(ProjectConstant.USER_PROFILE_OLD_PASSWORD);
		//String newPassword = (String)inputMap.get(ProjectConstant.USER_PROFILE_NEW_PASSWORD);
		UserBean user = processContext.getUserBean();
		Date currentDate = new Date();
		
		// Check oldPassword
/*		try {
			if(oldPassword != null && !"".equals(oldPassword) && !userProfile.getUspPassword().equals(encrypter.encrypt(oldPassword))){
				throw new BusinessException(ProjectConstant.MESSAGE_CODE_USP0001);
				
			}
			
			if(newPassword != null && !"".equals(newPassword))
				newPassword = encrypter.encrypt(newPassword);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
*/		
		// Update UserProfile into MASTER_USER_PROFILE
		logger.debug("1.Update UserProfile into MASTER_USER_PROFILE.");
		
/*		if(newPassword != null && !"".equals(newPassword))
			userProfile.setUspPassword(newPassword); // Change Password
*/		
		/*userProfile.setUspCreatedDate(new Timestamp(currentDate.getTime()));
		userProfile.setUspCreatedBy(user.getUsername());
		userProfile.setUspLastUpdatedDate(new Timestamp(currentDate.getTime()));
		userProfile.setUspLastUpdatedBy(user.getUsername());
		commonDAO.update(userProfile);
		commonDAO.flush();*/
		
		userProfileManagementDAO.updateUserProfile(userProfile, user.getUsername(), currentDate);
		
		// Update Or Insert Roles
		logger.debug("2.Update/Insert Roles into MASTER_USER_PROFILE.");
		MasterUserGroupToUserProfile criteria = new MasterUserGroupToUserProfile();
		criteria.setUspId(userProfile.getUspId().intValue());
		
		List<MasterUserGroupToUserProfile> currentRoles = (List<MasterUserGroupToUserProfile>)commonDAO.findByExample(criteria);
		List<Integer> assignedRolesList = new ArrayList<Integer>();
		boolean foundSameRole = false;
		MasterUserGroupToUserProfile usgToUsp = null;
		
		for(String s : assignedRoles){
			assignedRolesList.add(Integer.parseInt(s));
			
		}
		
		for(MasterUserGroupToUserProfile cRole : currentRoles){
			
			if(assignedRolesList.size() != 0){
				for(Integer aRole : assignedRolesList){
					if(cRole.getUsgId().intValue() == aRole.intValue()){
						foundSameRole = true;
						
						if(cRole.getUgpStatus().equals(ProjectConstant.INACTIVE_FLAG)){
							logger.debug("--> Active role : " + cRole.getUgpStatus());
							// Set UGP_STATUS from I [Inactive] to A [Active]
							cRole.setUgpStatus(ProjectConstant.ACTIVE_FLAG);
							/*cRole.setUgpCreatedDate(new Timestamp(currentDate.getTime()));
							userProfile.setUspCreatedBy(user.getUsername());*/
							cRole.setUgpLastUpdatedDate(new Timestamp(currentDate.getTime()));
							cRole.setUgpLastUpdatedBy(user.getUsername());
							commonDAO.update(cRole);
						}
						
						assignedRolesList.remove(aRole);
						break;
					}
					
				}
				
			}
			
			if(!foundSameRole){
				// Remove role case
				// Set UGP_STATUS from A [Active] to I [Inactive]
				logger.debug("--> Inactive role : " + cRole.getUgpStatus());
				cRole.setUgpStatus(ProjectConstant.INACTIVE_FLAG);
				/*cRole.setUgpCreatedDate(new Timestamp(currentDate.getTime()));
				userProfile.setUspCreatedBy(user.getUsername());*/
				cRole.setUgpLastUpdatedDate(new Timestamp(currentDate.getTime()));
				cRole.setUgpLastUpdatedBy(user.getUsername());
				commonDAO.update(cRole);
				
			}
			
			foundSameRole = false;
			
		}
		
		if(assignedRolesList.size() != 0){
			// Insert new role into DB
			for(Integer roleId : assignedRolesList){
				logger.debug("--> roleId : " + roleId);
				usgToUsp = new MasterUserGroupToUserProfile();
				
				usgToUsp.setUsgId(new Integer(roleId));
				usgToUsp.setUspId(userProfile.getUspId());
				usgToUsp.setUgpStatus(userProfile.getUspStatus());
				usgToUsp.setUgpCreatedDate(new Timestamp(currentDate.getTime()));
				usgToUsp.setUgpCreatedBy(user.getUsername());
				//usgToUsp.setUgpLastUpdatedDate(new Timestamp(currentDate.getTime()));
				//usgToUsp.setUgpLastUpdatedBy(user.getUsername());
				commonDAO.save(usgToUsp);
				
			}
			
		}
		
	}
	
}
